package com.ken.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ken.constant.JwtClaimsConstant;
import com.ken.context.BaseContext;
import com.ken.dto.EmployeeDTO;
import com.ken.dto.EmployeeLoginDTO;
import com.ken.dto.EmployeePageQueryDTO;
import com.ken.entity.Employee;
import com.ken.properties.JwtProperties;
import com.ken.result.PageResult;
import com.ken.result.Result;
import com.ken.service.EmployeeService;
import com.ken.utils.JwtUtil;
import com.ken.vo.EmployeeLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 员工管理
 */
@RestController
@RequestMapping("/admin/employee")
@Slf4j
@Api(tags = "员工相关接口")
public class EmployeeController{

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "员工登录功能")
    public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO) {
        log.info("员工登录：{}", employeeLoginDTO);

        Employee employee = employeeService.login(employeeLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .name(employee.getName())
                .token(token)
                .build();

        return Result.success(employeeLoginVO);
    }

    /**
     * 退出
     *
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation("员工退出功能")
    public Result<String> logout() {
        return Result.success();
    }

    /**
     * 新增员工功能
     * @param employeeDTO
     * @return
     */
    @PostMapping
    @ApiOperation("新增员工功能")
    public Result<EmployeeDTO> insertEmployee(@RequestBody EmployeeDTO employeeDTO){
        log.info("新增员工：{}",employeeDTO);
        employeeService.insertEmployee(employeeDTO);
        return Result.success();
    }

    /**
     * 员工分页查询
     * @param employeePageQueryDTO
     * @return
     */
    @GetMapping("/page")
    @ApiOperation("员工分页查询")
    public Result<PageResult> employeePageQuery(EmployeePageQueryDTO employeePageQueryDTO){
        log.info("员工分页查询，参数为：{}", employeePageQueryDTO);
        Page<Employee> page=employeeService.query()
                .like(StrUtil.isNotBlank(employeePageQueryDTO.getName()),"name",employeePageQueryDTO.getName())
                .page(new Page<>(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize()));
        return Result.success(new PageResult(page.getTotal(),page.getRecords()));
    }

    /**
     * 启用、禁用员工账号
     * @param status
     * @param id
     * @return
     */
    @PostMapping("/status/{status}")
    @ApiOperation("启用、禁用员工账号")
    public Result<String> employerStatus(@PathVariable String status,@RequestParam String id){
        Employee employee=new Employee();
        employee.setId(Long.valueOf(id));
        employee.setStatus(Integer.valueOf(status));
        employeeService.updateById(employee);
        return Result.success();
    }

    /**
     * 根据id查询员工
     * @param id
     * @return
     */
    @GetMapping("{id}")
    @ApiOperation("根据id查询员工")
    public Result<Employee> selectById(@PathVariable String id){
        return Result.success(employeeService.getById(id));
    }

    /**
     * 编辑员工信息
     * @param employeeDTO
     * @return
     */
    @PutMapping
    @ApiOperation("编辑员工信息")
    public Result<String> employeeInfoUpdate(@RequestBody EmployeeDTO employeeDTO){
        log.info("编辑员工信息：{}", employeeDTO);
        // 验证id是否有效
        if(employeeDTO.getId() == null || employeeDTO.getId() <= 0) {
            return Result.error("员工ID无效");
        }
        Employee employee = new Employee();
        BeanUtil.copyProperties(employeeDTO, employee, true);
        employee.setUpdateUser(BaseContext.getCurrentId());
        employee.setUpdateTime(LocalDateTime.now());
        boolean updated = employeeService.updateById(employee);
        if(!updated) {
            return Result.error("员工信息更新失败，员工不存在");
        }
        return Result.success();
    }
}
